package com.htht.smartschool.service.user;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.client.ClientProtocolException;

import com.google.gson.internal.LinkedTreeMap;
import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.dao.user.UserDao;
import com.htht.smartschool.model.card.TCard;
import com.htht.smartschool.model.models.Models;
import com.htht.smartschool.model.push.PushResult;
import com.htht.smartschool.model.push.PushUser;
import com.htht.smartschool.model.roles.Role;
import com.htht.smartschool.model.student.TStudent;
import com.htht.smartschool.model.teacher.TClass;
import com.htht.smartschool.model.user.TUser;
import com.htht.smartschool.service.license.LicenseService;
import com.htht.smartschool.util.http.HttpUtil;
import com.htht.smartschool.util.redis.RedisKeyConstant;
import com.htht.smartschool.util.redis.RedisUtil;
import com.htht.smartschool.util.system.ConfigUtil;
import com.htht.smartschool.util.system.EncryptUtil;
import com.htht.smartschool.util.system.GsonUtils;
import com.htht.smartschool.util.system.ImgUtil;

public class UserService extends BaseService {
	private Map addPeriodMap = new HashMap() ;
	private Map addGradeMap = new HashMap();
	private Map addClassesMap = new HashMap();
	UserDao userDao = new UserDao();
	LicenseService license = new LicenseService();
	/***
	 * 注册用户
	 * @param tuser
	 * @return
	 */
	public TUser register(TUser tuser) {
		TUser user = getUserDetail(tuser.getUsercode(),tuser.getUsertype());
		if (user != null) {
			return null;
		}else{
			tuser.setPassword(EncryptUtil.encryptMd5Password2(tuser.getPassword()));
			tuser.setUserkey(EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype()));
			tuser = (TUser) getDao().create(tuser);
			return tuser;
		}
	}
	/***
	 * web端管理员注册用户
	 * @param tuser
	 * @return
	 */
	@SuppressWarnings("unused")
	public TUser webRegister(TUser tuser,Role role) {
		TUser user = getWebUserDetail(tuser.getUsercode(),tuser.getUsertype());
		if (user != null) {
			return null;
		}else{
			tuser.setPassword(EncryptUtil.encryptMd5Password2(tuser.getPassword()));
			tuser.setUserkey(EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype()));
			String mesid = regPushUser(tuser.getUsercode()+tuser.getUsertype(),tuser.getUsertype());
			tuser.setMessageid(mesid);
			if(tuser.getHeadimg() != null && tuser.getHeadimg().length() > 0){
				Date date = new Date();
				String filepath = ImgUtil.usersimgpath+"/"+tuser.getUserkey()+"/"+date.getTime()+".png";
				String fileurl = ConfigUtil.getProperty("default","usersfile")+tuser.getUserkey()+"/"+date.getTime()+".png";
				File file = new File(ImgUtil.usersimgpath+"/"+tuser.getUserkey());
				ImgUtil.base64StringToImage(tuser.getHeadimg(), filepath,file);
				tuser.setHeadimg(fileurl);
			}else{
				tuser.setHeadimg(ConfigUtil.getProperty("default","headimg"));
			}
			tuser = (TUser) getDao().create(tuser);
			if(tuser.getUsertype() == 1){
				String studentcodes = tuser.getStudentcode();
				String[] stCodeArr = studentcodes.split(",");
				String imeiStrings = tuser.getStumeis();
				String[] imeiArr = imeiStrings.split(",");
				for(int i = 0; i < stCodeArr.length; i++){
					String delSql = "delete from t_user_student where usercode = :usercode and studentcode = :studentcode";
					tuser.setStudentcode(stCodeArr[i]);
					getDao().executeSQL(delSql,tuser);
					String sql = "insert into t_user_student (id,usercode,studentcode,imei) values (null,:usercode,:studentcode,:imei)";
					tuser.setImei(imeiArr[i]);
					getDao().executeSQL(sql,tuser);
				}
			}
//			if(tuser.getUsertype() == 0){//将管理员与角色绑定
//				String userkey = EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype());
//				String sql = "insert into t_role_user values(null,:code,'"+userkey+"')";
//				getDao().executeSQL(sql,role);
//			}
			if(tuser.getMainType() != null){//将运维与角色绑定 超级管理员
				String userkey = EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype());
				String qsql = "select max(id) from t_role_user";
				List list = getDao().queryBySQL(qsql);
				//获取将最大id值作为code值
				String rolecode =  String.valueOf(list.get(0));			
//				Object[] obje =  (Object[]) list.get(0);
//				String rolecode = String.valueOf(obje[0]);
				if(rolecode == null || rolecode.equalsIgnoreCase("null")){
					rolecode = "1";
				}else{
					rolecode = String.valueOf(Integer.parseInt(rolecode)+1);
				}
				//给新学校绑定新角色
				String sql = "insert into t_role (id,schoolcode,code,name,remark) values(null,'"+tuser.getSchoolcode()+"','"+rolecode+"','超级管理员','"+tuser.getRemark()+"');";
				getDao().executeSQL(sql);
				//将角色与用户绑定
				String bsql = "insert into t_role_user values(null,'"+rolecode+"','"+userkey+"')";
				getDao().executeSQL(bsql,role);
				List<Models> result = queryModels();//查出所有的models的code
				for(int j = 0;j<result.size();j++){//将这个新建的用户绑定所有模块  具备查看所有模块的权限
					Models mo = result.get(j);
					String lisql = " insert into t_license(rolecode,modular) values ('"+rolecode+"','"+mo.getCode()+"')";
					getDao().executeSQL(lisql);
				}
				//查看这个学校有没有班级 如果有的话 就给授权
				String clsql = " select classcode,grade,class from t_class where schoolcode = '"+tuser.getSchoolcode()+"'";
				List cllist = getDao().queryBySQL(clsql);
				if(cllist.size() > 0){
					for(int k = 0;k<cllist.size();k++){
						Object[] obj = (Object[]) cllist.get(k);
						//给角色授权数据
						String isql = "insert into t_data_role(rolecode,classcode,grade,classes) values('"+rolecode+"','"+String.valueOf(obj[0])+"','"+String.valueOf(obj[1])+"','"+String.valueOf(obj[2])+"')";
						getDao().executeSQL(isql);
					}
					
				}
			}
		}
		return tuser;
	}
	/**
	 * 查询所有模块接口
	 * @author:wuqiwei
	 * @param @return
	 * @date:2016年6月12日下午5:25:24
	 */
	public List<Models> queryModels(){
		String sql = "select id,code from t_models";
		List list = getDao().queryBySQL(sql);
		List<Models> result = new ArrayList<Models>();
		for (int i = 0;i<list.size();i++) {
			Object[] obj = (Object[]) list.get(i);
			Models mo = new Models();
			mo.setCode((String) obj[1]);
			result.add(mo);
		}
		return result;
	}
	/**
	 * 判断数据库是否存在
	 * 
	 * @param usercode
	 * @return
	 */
	public TUser getUserDetail(String usercode,int usertype) {
		TUser user = null;
		TUser tuser = new TUser();
		try {
			String hql = String.format("from TUser where %1$s='%2$s' and %3$s='%4$s'", "usercode", usercode,"usertype", usertype);
			tuser.setUsercode(usercode);
			tuser.setUsertype(usertype);
			user = (TUser) getDao().queryFirstByHQL(hql,tuser);
			if (user == null) {
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	
	public TUser getUserDetail(String usercode) {
		TUser user = null;
		try {
			String hql = String.format("from TUser where %1$s='%2$s'", "usercode", usercode);
			user = (TUser) getDao().queryFirstByHQL(hql);
			if (user == null) {
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	@SuppressWarnings("unchecked")
	public Map<String,List<Long>> getTeachersMess(String usercode) {
		Map<String,List<Long>> result = new HashMap<String, List<Long>>();
		try {
			String conditions = "=";
			if(usercode.contains(",")){
				conditions = "in";
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("usercode", usercode);
			String hql = "from TUser where usertype = 2 and usercode "+conditions+" :usercode";
			List<Long> list = new ArrayList<Long>();
			List<Long> list2 = new ArrayList<Long>();
			List<TUser> users = getDao().queryByHQL(hql, map);
			if (users.size() == 0) {
				return null;
			}else{
				for (TUser tu : users) {
					list2.add(Long.valueOf(tu.getCellphone()));
				}
				result.put("messageids", list);
				result.put("cellphones", list2);
				return result;
			}
		} catch (Exception e) {
			return null;
		}
	}
	@SuppressWarnings("unchecked")
	public Map<String,List<Long>> getStudentsMess(String usercode) {
		Map<String,List<Long>> result = new HashMap<String, List<Long>>();
		try {
			String conditions = "=";
			if(usercode.contains(",")){
				conditions = "in";
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("studentcode", usercode);
			String hql = "select tu from TUser tu,TStudent ts,TUserStudent tus where"
					+ " tu.usertype = 1 and tu.usercode = tus.usercode and ts.studentcode = tus.studentcode and ts.studentcode "+conditions+" :studentcode";
			List<Long> list = new ArrayList<Long>();
			List<Long> list2 = new ArrayList<Long>();
			List<TUser> users = getDao().queryByHQL(hql, map);
			if (users.size() == 0) {
				return null;
			}else{
				for (TUser tu : users) {
					list.add(Long.valueOf(tu.getMessageid()));
					list2.add(Long.valueOf(tu.getCellphone()));
				}
				result.put("messageids", list);
				result.put("cellphones", list2);
				return result;
			}
		} catch (Exception e) {
			return null;
		}
	}
	public TUser getWebUserDetail(String usercode,int usertype) {
		TUser user = null;
		try {
			String hql = String.format("from TUser where usercode = '" + usercode + "' and usertype = " + usertype + "");
			user = (TUser) getDao().queryFirstByHQL(hql);
			if (user == null) {
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	/**
	 * 用户登录
	 * @param tuser
	 * @return
	 */
	public TUser login(TUser tuser) {
		String epass = EncryptUtil.encryptMd5Password2(tuser.getPassword());
		String ekey = EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype());
		String hql = String.format("from TUser where userkey='%1$s' and password='%2$s' and usertype=%3$s", ekey, epass, tuser.getUsertype());
		TUser user = (TUser) getDao().queryFirstByHQL(hql);
		String sessionid = "";
		if (user == null || user.getIslock() == false) {
			return null;
		}else{
			if(tuser.getImei()!=null && tuser.getImei().length()>0){
				if(tuser.getDeviceToken() != null && tuser.getDeviceToken().length() > 0){
					sessionid = pushLogin(user.getUsercode()+user.getUsertype(),user.getUsertype(),tuser.getImei(),tuser.getDeviceToken());
					user = shieldUserInfo(user);
//					RedisUtil.getInstance().setString(RedisKeyConstant.STARTLINEDATE, String.valueOf(new Date().getTime()));
//					RedisUtil.getInstance().setString(RedisKeyConstant.LASTONLINEDATE, String.valueOf(new Date().getTime()));
//					UserOnlineUtil.online(user);
					user.setPushsessionid(sessionid);
					return user;
				}else{
					sessionid = pushLogin(user.getUsercode()+user.getUsertype(),user.getUsertype(),tuser.getImei(),null);
					user = shieldUserInfo(user);
//					RedisUtil.getInstance().setString(RedisKeyConstant.STARTLINEDATE, String.valueOf(new Date().getTime()));
//					RedisUtil.getInstance().setString(RedisKeyConstant.LASTONLINEDATE, String.valueOf(new Date().getTime()));
//					UserOnlineUtil.online(user);
					user.setPushsessionid(sessionid);
					return user;
				}
			}else{
				return null;
			}
			
		} 
		
	}
	public List mainTest() {
		String hql = "From TUser where usertype=2";
		List<TUser> list = getDao().queryByHQL(hql, null);
		for (TUser user : list) {
//			String s =pushLogin(user.getUsercode()+"2", 2, "0874284C-7BC1-4A1B-ACEC-7AAE38F3942A",null);
//			String d = getPushUser(s,user.getUsercode()+"2");
//			String sql = "update t_user set messageid = '"+d+"' where id = "+user.getId();
//			getDao().executeSQL(sql);
		}
		List<TUser> list2 = getDao().queryByHQL(hql, null);
		return list2;
	}
	public boolean loginout(String pushsessionid) {
		boolean result = false;
		String url =ConfigUtil.getProperty("message","url")+"user/logout?sessionid="+pushsessionid;
		try {
			String resultStr = HttpUtil.getInstance().doGet(url);
			PushResult pr = (PushResult) GsonUtils.getInstance().fromJson(resultStr, PushResult.class);
			result = pr.getResult();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	public boolean verifyPushUser(String uuid,String token){
		boolean result = false;
		String url =ConfigUtil.getProperty("message","url")+"push/settoken?sessionid="+uuid+"&token="+token;
		try {
			String resultStr = HttpUtil.getInstance().doGet(url);
			PushResult pr = (PushResult) GsonUtils.getInstance().fromJson(resultStr, PushResult.class);
			if(pr.getResult()){
				String flag = (String) pr.getData();
				if(flag.equalsIgnoreCase("OK")){
					result = true;
				}
			}else{
				loginout(uuid);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
//	@SuppressWarnings("unchecked")
//	public static void main(String[] args) {
//		DataBaseManager.getInst();
//		BaseDao bd = new BaseDao();
//		List<Object[]> list = bd.queryBySQL("SELECT usercode,usertype,id FROM t_user ");
//		for (Object[] obj : list) {
//			String code = String.valueOf(obj[0]);
//			String type = String.valueOf(obj[1]);
//			String msid = regPushUser(code+type,Integer.parseInt(type));
//			String sql = "UPDATE t_user SET messageid='"+msid+"' WHERE id='"+String.valueOf(obj[2])+"';";
//			int i = bd.executeSQL(sql);
//			if(i != -1){
//				System.out.println("ture-----------"+code);
//			}else{
//				System.out.println("false-----------"+code);
//			}
//		}
////		verifyPushUser("10027","26231a955ba9e973c7268aea5fca9f941ad52c9d0aabe34ff562ab0249825a35");
////		regPushUser("187135623112");
////		regPushUser("156527123161",1);
////		System.out.println(EncryptUtil.encryptMd5Password2("156527123181"));
////		loginout("72cf732dae7919b23c3c629877f00314");
//	}
	public String regPushUser(String usercode,int usertype){
		String mesid = null;
		String params = "";
		try {
			PushUser pu = new PushUser();
			pu.setUsername(usercode);
			pu.setPassword(usercode);
			pu.setAdmin(false);
			pu.setAppid(Integer.parseInt(ConfigUtil.getProperty("message","userid")));
			if(usertype == 2){
				pu.setAppid(Integer.parseInt(ConfigUtil.getProperty("message","teacherid")));
			}
			pu.setAddress("");
			pu.setDepid(0);
			pu.setEmail("");
			pu.setNikename("");
			pu.setRole("");
			pu.setSex("");
			pu.setStatus("");
			pu.setTel("");
			params = GsonUtils.getInstance().toJson(pu);
			String result = HttpUtil.getInstance().doPostJson(ConfigUtil.getProperty("message","url")+"user/signup", params);
			PushResult pr = (PushResult) GsonUtils.getInstance().fromJson(result, PushResult.class);
			if(pr.getResult()){
				Double mesidD = (Double)pr.getData();
				mesid = String.valueOf(mesidD.intValue());
			}else{
				mesid = String.valueOf(pr.getResult());
			}
			System.out.println(mesid);
			if(mesid.equals("false")){
				mesid = "0";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mesid;
	}
	public static void main(String[] args) {
		UserService us = new UserService();
		String s = us.pushLogin("186100735532", 2, "0874284C-7BC1-4A1B-ACEC-7AAE38F3942A",null);
		us.getPushUser(s,"186100735532");
	}
	public String getPushUser(String sessionid,String username){
		String url =ConfigUtil.getProperty("message","url")+"user/getuserinfo?sessionid="+sessionid;
		try {
			sessionid = HttpUtil.getInstance().doGet(url);
			if(sessionid.contains("Uid")){
				String[] s = sessionid.split("\"Uid\":");
				sessionid= s[1].split(",")[0];
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(sessionid.trim());
		return sessionid.trim();
	}
	@SuppressWarnings("rawtypes")
	public String pushLogin(String usercode,int usertype,String imei,String token){
		String sessionid = null;
		String url =ConfigUtil.getProperty("message","url")+"user/login?username="+usercode+"&password="+usercode+"&appid=";
		if(usertype == 2){
			url = url +Integer.parseInt(ConfigUtil.getProperty("message","teacherid"));
		}else{
			url = url +Integer.parseInt(ConfigUtil.getProperty("message","userid"));
		}
		if(token == null){
			url += "&mac="+imei;
		}else{
			url += "&mac="+imei +"&token="+token;
		}
		System.out.println(imei);
		try {
			String result = HttpUtil.getInstance().doGet(url);
			PushResult pr = (PushResult) GsonUtils.getInstance().fromJson(result, PushResult.class);
			if(pr.getResult()){
				LinkedTreeMap ltm = (LinkedTreeMap) pr.getData();
				Set set = ltm.entrySet();
				for (Object obj : set) {
					sessionid = obj.toString();
					if(sessionid.contains("sessionid")){
						sessionid = sessionid.split("=")[1];
					}
				}
			}else{
				sessionid = String.valueOf(pr.getResult());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sessionid;
	}
	public TUser shieldUserInfo(TUser user){
		user.setPassword("");
		user.setIslock(null);
		user.setRegion("");
		user.setUsertype(null);
		user.setModel("");
		user.setAndroid("");
		user.setImei("");
		user.setRegtype(null);
		user.setVcode("");
		return user;
	}
	/**
	 * 根据用户编码获取学生信息
	 * @param usercode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TStudent> getStudentByUserCode(String usercode) {
		addPeriod();
		String sql = "SELECT DISTINCT ts FROM TUserStudent AS us ,TStudent AS ts WHERE us.studentcode = ts.studentcode and us.usercode = :usercode";
		List<TStudent> list =  getDao().getSession().createQuery(sql)
                .setString("usercode",usercode)
                .list();
		List<TStudent> result = new ArrayList<TStudent>();
		for (TStudent ts : list) {
			//通过classcode是唯一的  将classcode作为key值  type grade classes作为value
			String classcode = (String) addPeriodMap.get(ts.getClasscode());
			Integer grade =  (Integer) addGradeMap.get(ts.getClasscode());
			String classes = (String) addClassesMap.get(ts.getClasscode());
			ts.setPeriodtype(classcode);
			ts.setGrade(grade);
			ts.setClasses(classes);
			String rfidsql = "From TCard where studentcode = :studentcode";
			List<TCard> rfids = getDao().getSession().createQuery(rfidsql)
                     .setString("studentcode", ts.getStudentcode())
                     .list();
			TCard tc =null; 
			String gradesql = "From TClass where classcode = :classcode";
			List<TClass> grades = getDao().getSession().createQuery(gradesql)
						.setString("classcode", ts.getClasscode())
						.list();
			TClass tclass = null;
			if(grades.size()>0){
				tclass = grades.get(0);
			}
			if(rfids.size() > 0){
				tc = rfids.get(0);
			}
			if(tc != null){
				ts.setRfid(tc.getCardcode());
				ts.setImei(tc.getImei());
			}
			if(tclass!=null){
				ts.setGrade(tclass.getGrade());
			}
			result.add(ts);
		}
		return result;
	}
	/**
	 * 添加学段 添加班级信息
	 * @author:wuqiwei
	 * @param 
	 * @date:2016年6月17日下午5:25:46
	 */
	public void addPeriod(){
		String hql = " FROM TClass";
		List<TClass> list = getDao().queryByHQL(hql);
		for(int i = 0;i<list.size();i++){
			TClass cl = list.get(i);
			addPeriodMap.put(cl.getClasscode(),cl.getType());//将classcode作为key,type作为value
			addGradeMap.put(cl.getClasscode(), cl.getGrade());
			addClassesMap.put(cl.getClasscode(), cl.getClasses());
		}
	}
	/**
	 * 修改用户密码
	 * @param tuser
	 * @return
	 */
	public TUser updateInfo(TUser tuser) {
		TUser user = getUserDetail(tuser.getUsercode(),tuser.getUsertype());
		if(tuser.getPassword() != null && tuser.getPassword().length() > 0){
				if(tuser.getOldpassword() == null && tuser.getPassword().length() == 0){
					return null;
				}else{
					String newpass = EncryptUtil.encryptMd5Password2(tuser.getPassword());
					String oldpass = EncryptUtil.encryptMd5Password2(tuser.getOldpassword());
					if(!user.getPassword().equalsIgnoreCase(newpass) && user.getPassword().equalsIgnoreCase(oldpass)){
						tuser.setPassword(newpass);
					}else{
						return null;
					}
				}
		}
		if (user != null) {
			if(tuser.getHeadimg() != null && tuser.getHeadimg().length() > 0){
				ImgUtil.remove(ImgUtil.usersimgpath+"/"+user.getUserkey(),user.getHeadimg());
				Date date = new Date();
				String filepath = ImgUtil.usersimgpath+"/"+user.getUserkey()+"/"+date.getTime()+".png";
				String fileurl = ConfigUtil.getProperty("default","usersfile")+user.getUserkey()+"/"+date.getTime()+".png";
				File file = new File(ImgUtil.usersimgpath+"/"+user.getUserkey());
				ImgUtil.base64StringToImage(tuser.getHeadimg(), filepath,file);
				tuser.setHeadimg(fileurl);
			}
			for (Field f : tuser.getClass().getDeclaredFields()) {
			    f.setAccessible(true);
			    try {
					if (f.get(tuser) != null && !f.get(tuser).equals("") && !f.getName().equalsIgnoreCase("serialVersionUID")) {
					   f.set(user, f.get(tuser));
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			tuser = (TUser) getDao().update(user);
			return tuser;
		}else{
			return null;
		}
	}
	/**
	 * 修改用户信息
	 * @param tuser
	 * @return
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	public TUser updateUserInfo(TUser tuser) {
		TUser user = getUserDetail(tuser.getUsercode(),tuser.getUsertype());
		tuser.setUserkey(EncryptUtil.encryptMd5Password2(tuser.getUsercode()+tuser.getUsertype()));
		if(tuser.getPassword() != null && tuser.getPassword().length() > 0){
			tuser.setPassword(EncryptUtil.encryptMd5Password2(tuser.getPassword()));
		}
		if (user != null) {
			if(tuser.getHeadimg() != null && tuser.getHeadimg().length() > 0){
				ImgUtil.remove(ImgUtil.usersimgpath+"/"+user.getUserkey(),user.getHeadimg());
				Date date = new Date();
				String filepath = ImgUtil.usersimgpath+"/"+user.getUserkey()+"/"+date.getTime()+".png";
				String fileurl = ConfigUtil.getProperty("default","usersfile")+user.getUserkey()+"/"+date.getTime()+".png";
				File file = new File(ImgUtil.usersimgpath+"/"+user.getUserkey());
				ImgUtil.base64StringToImage(tuser.getHeadimg(), filepath,file);
				tuser.setHeadimg(fileurl);
			}
			for (Field f : tuser.getClass().getDeclaredFields()) {
			    f.setAccessible(true);
			    try {
					if (f.get(tuser) != null && !f.get(tuser).equals("") && !f.getName().equalsIgnoreCase("serialVersionUID")) {
					   f.set(user, f.get(tuser));
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			if(tuser.getUsertype() == 1){
				String studentcodes = tuser.getStudentcode();
				String[] stCodeArr = studentcodes.split(",");
				String imeiStrings = tuser.getStumeis();
				String delSql = "delete from t_user_student where usercode = :usercode";
				getDao().executeSQL(delSql,tuser);
				String[] imeiArr = null;
				if(imeiStrings != null){
					imeiArr = imeiStrings.split(",");
					for (int j = 0; j < imeiArr.length; j++) {
						String sql = "insert into t_user_student (id,usercode,studentcode,imei) values (null,:usercode,'" + stCodeArr[j] + "','" + imeiArr[j] + "')";
						getDao().executeSQL(sql,tuser);
					}
				}else{
					for (int j = 0; j < stCodeArr.length; j++) {
						String sql = "insert into t_user_student (id,usercode,studentcode,imei) values (null,:usercode,'" + stCodeArr[j] + "',null)";
						getDao().executeSQL(sql,tuser);
					}
				}
				
				
				
//				String[] imeiArr = imeiStrings.split(",");
//				String delSql = "delete from t_user_student where usercode = :usercode";
//				getDao().executeSQL(delSql,tuser);
//				for (int j = 0; j < imeiArr.length; j++) {
//					String sql = "insert into t_user_student (id,usercode,studentcode,imei) values (null,:usercode,'" + stCodeArr[j] + "','" + imeiArr[j] + "')";
//					getDao().executeSQL(sql,tuser);
//				}
			}
			if(tuser.getUsertype() == 0){//将管理员与角色绑定
				String sql = "delete from t_role_user where rolecode = :code and userkey = :userkey";//不管有没有先删除在添加
				getDao().executeSQL(sql,tuser);
				String sql1 = "insert into t_role_user values(null,:code,:userkey)";
				getDao().executeSQL(sql1,tuser);
			}
			tuser = (TUser) getDao().update(user);
			return tuser;
		}else{
			return null;
		}
	}
	/**
	 * 用于用户注册时验证用户名
	 * @param usercode
	 * @return
	 */
	public boolean verifyByUsercode(String usercode,int usertype) {
		TUser user = getUserDetail(usercode,usertype);
		if(user == null){
			return true;
		}else{
			return false;
		}
		
	}
	
	/***
	 * 分页获取用户信息，通过用户姓名检索用户信息
	 * @param currentpage
	 * @param pagesize
	 * @param name
	 * @return map
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	public Map getUsersByPageAndAttr(TUser user){
		Map map = new HashMap();
		
		String nameSql = "";
		String usertypeSql="";
		String nameHql = "";
		String usertypeHql = "";
		if(user.getName() != null){
			nameSql = " and alias like :name";
			nameHql = " and alias like :name";
			user.setName("%"+user.getName()+"%");
		}
		
		String islocked = "";
		if(user.getIslock()){
			islocked = "1";
		}else{
			islocked = "0";
		}
		if(user.getUsertype() != 10){
			usertypeSql = " and usertype = :usertype";
			usertypeHql = " and usertype = :usertype";
		}
		String hql = "from TUser where islock = '"+islocked+"'" + usertypeHql + nameHql;
		String sql = "select count(*) from t_user where islock = '"+islocked+"'" + usertypeSql + nameSql;
		List<TUser> list = getDao().queryByHQLPage(hql,user, user.getCurrentpage(), user.getPagesize());
		int count = getDao().getCountBySqlPage(sql,user);
		
		map.put("total", count);
		map.put("data", list);
		return map;
	}
	/***
	 * 锁定用户，批量锁定用户
	 * @param usercodes
	 * @return flag
	 */
	@SuppressWarnings("rawtypes")
	public boolean lockUserByUsercodes(TUser tuser){
		boolean flag = true;
		String values = "";
		List list = tuser.getUsercodes();
		for(int i = 0; i < list.size(); i++){
			values += "'"+list.get(i) + "',";
		}
		values = values.substring(0,values.length() - 1);
		String sql = "update t_user set islock = '0',lockdate = :lockdate where usercode in (" + values + ")";
		int ud = getDao().executeSQL(sql,tuser);
		if(ud == -1){
			flag = false;
		}
		return flag;
	}
	/***
	 * 解锁用户
	 * @param usercode
	 * @return flag
	 */
	public boolean unlockUserByUsercodes(TUser tuser){
		boolean flag = true;
		String sql = "update t_user set islock = '1',lockdate = 0 where usercode = :usercode";
		int ud = getDao().executeSQL(sql,tuser);
		if(ud == -1){
			flag = false;
		}
		return flag;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getAllUserWithStudent(TUser tuser){
		String sql = "SELECT DISTINCT tu.*,info.stucodes,info.imeis,info.stunames,te.*,ts.name schoolname"
				+ " FROM t_user tu LEFT JOIN (SELECT * FROM t_school) ts ON tu.schoolcode = ts.schoolcode LEFT JOIN (SELECT tus.usercode,GROUP_CONCAT(tus.studentcode) stucodes,GROUP_CONCAT(tus.imei) imeis,GROUP_CONCAT(ts.name) stunames FROM t_user_student tus,t_student ts WHERE tus.studentcode = ts.studentcode ";
				if(tuser.getUsertype() != 0){
					sql += " AND ts.schoolid = '"+tuser.getSchoolcode()+"'";
				}
				sql+= " GROUP BY tus.usercode)info"
				+ " ON tu.usercode = info.usercode "
				+ " LEFT JOIN(SELECT tru.rolecode,tru.userkey FROM t_role_user tru) tr "
				+ " ON tu.userkey = tr.userkey "
				+ " LEFT JOIN (SELECT tro.code,tro.name FROM t_role tro) te "
				+ " ON te.code = tr.rolecode ";
//				+ " LEFT JOIN(SELECT tdu.departmentcode,tdu.userkey FROM t_departmentcode_user tdu) td"
//				+ " ON tu.userkey = td.userkey"
//				+ " LEFT JOIN(SELECT tp.departmentcode,tp.department,tp.office FROM t_department tp) tdp"
//				+ " ON tdp.departmentcode = td.departmentcode";
		boolean s = true;
		if(tuser.getIslock()!=null){
			String islock = "0";
			if(tuser.getIslock()){
				islock = "1";
			}
			sql += " where tu.islock = '"+islock + "' ";
			s = false;
		}
		if(tuser.getUsertype()!=null && tuser.getUsertype() != 10){
			if(s){
				sql += " where tu.usertype = :usertype ";
			}else{
				sql += " and tu.usertype = :usertype ";
			}
			s = false;
		}
		if(tuser.getAlias()!=null && tuser.getAlias().length() > 0){
			if(s){
				sql += " where tu.alias like :alias ";
				tuser.setAlias("%"+tuser.getAlias()+"%");
			}else{
				sql += " and tu.alias like :alias ";
				tuser.setAlias("%"+tuser.getAlias()+"%");
			}
			s = false;
		}
		if(tuser.getSchoolcode() != null && tuser.getSchoolcode().length() > 0 ){
			if(s){
				sql += " where tu.schoolcode = :schoolcode";
			}else{
				sql += " and tu.schoolcode = :schoolcode";
			}
		}
		sql += "  ORDER BY tu.usercode asc";
		int total = 0;
		List<Object[]> list = new ArrayList<Object[]>();
		if(tuser.getCurrentpage() == null && tuser.getPagesize() == null){
			list = getDao().queryBySQL(sql,tuser);
			total = list.size();
		}else{
			list = getDao().queryBySqlPage(sql,tuser, tuser.getCurrentpage(), tuser.getPagesize());
			total = getDao().getCountBySqlPage("select count(*) from("+sql+")tf",tuser);
		}
		List<TUser> re = new ArrayList<TUser>();
		Map map = new HashMap();
		TUser old = new TUser();
		for (Object[] obj : list) {
			TUser tu = new TUser();
			tu.setId(Long.valueOf(String.valueOf(obj[0])));
			tu.setUsercode(String.valueOf(obj[1]));
			tu.setAlias(String.valueOf(obj[4]));
			tu.setIslock(Integer.parseInt(String.valueOf(obj[5])) == 1 ? true :false);
			tu.setLockdate(Long.valueOf(String.valueOf(obj[6]) == "null" ? "0" :String.valueOf(obj[6])));
			tu.setLocktype(Integer.parseInt(String.valueOf(obj[7]) == "null" ? "0" :String.valueOf(obj[7])));
			tu.setRegion(String.valueOf(obj[8]));
			tu.setUsertype(Integer.parseInt(String.valueOf(obj[9]) == "null" ? "0" :String.valueOf(obj[9])));
			tu.setCellphone(String.valueOf(obj[10]));
			tu.setEmail(String.valueOf(obj[11]));
			tu.setRemark(String.valueOf(obj[12]));
			tu.setAddress(String.valueOf(obj[13]));
			tu.setModel(String.valueOf(obj[14]));
			tu.setAndroid(String.valueOf(obj[15]));
			tu.setImei(String.valueOf(obj[16]));
			tu.setRegtype(Integer.parseInt(String.valueOf(obj[17]) == "null" ? "0" :String.valueOf(obj[17])));
			tu.setVcode(String.valueOf(obj[18]));
			tu.setHeadimg(String.valueOf(obj[19]));
			tu.setMessageid(String.valueOf(obj[20]));
			tu.setRegtime(Long.valueOf(String.valueOf(obj[21]) == "null" ? "0" :String.valueOf(obj[21])));
			tu.setStucodes(String.valueOf(obj[23]));
			tu.setStuimeis(String.valueOf(obj[24]));
			tu.setStunames(String.valueOf(obj[25]));
//			tu.setUserkey(String.valueOf(obj[3]));
			tu.setSchoolcode(String.valueOf(obj[22]));
			tu.setCode(String.valueOf(obj[26]));
			tu.setName(String.valueOf(obj[27]));
			tu.setSchoolname(String.valueOf(obj[28]));
			re.add(tu);
//			if(tuser.getUsertype()!= null && tuser.getUsertype()== 0){
//				String newcode = tu.getUsercode();
//				String olcode = old.getUsercode();
//				if(newcode!= null && olcode != null && newcode.equalsIgnoreCase(olcode)){
//					String sqla = "select * from t_license where rolecode = '"+tu.getCode()+"'";
//					String sqlb = "select * from t_license where rolecode = '"+old.getCode()+"'";
//					List lista = getDao().queryBySQL(sqla);
//					List listb = getDao().queryBySQL(sqlb);
//					if(lista.size() > listb.size()){
//						re.remove(re.size()-1);
//						re.add(tu);
//					}
//				}else{
//					re.add(tu);
//				}
//				old = tu;
//			}else{
//				re.add(tu);
//			}
		}
		map.put("data", re);
		map.put("total", total);
		return map;
	}
	
	public Boolean deleteUser(TUser tuser){
		Boolean flag = false;
		String sql = "delete from t_user where usercode=:usercode";
		String[] sqls = new String[]{sql};
		int i = getDao().deleteSQL(sqls,tuser);
		if(i>0){
			//当删除家长用户的时候  将t_user_student表里的数据也一并删除
				String dsql = "delete from t_user_student where usercode =:usercode";
				String[] dsqll = new String[]{dsql};
				int a  = getDao().deleteSQL(dsqll,tuser);
				if( a >= 0){
					flag = true;
				}
		}
		return flag;
	}
	/**获取手机验证码
	 * @author:wuqiwei
	 * @param @return
	 * @date:2015年12月4日上午11:18:04
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean getCode(TUser tuser) {
		//判断用户存在不存在
		TUser user = getUserDetail(tuser.getUsercode(),tuser.getUsertype());
		if(user !=null){
			//获取六位随机数
			int code = (int)((Math.random()*9+1)*100000);
			//String url ="http://120.25.0.124:8080/cmppweb/send.do";
			String url = ConfigUtil.getProperty("phoneVerification", "url");
			String param = "param";
			String number = tuser.getUsercode();
			//判断number是不是纯数字
			boolean result=number.matches("[0-9]+");
			if(result){
				//在判断是不是11位
				if(number.length() == 11){
					Map map = new HashMap();
					map.put("to", number);
					map.put("content", "手机验证码："+code+"");
					String content = GsonUtils.getInstance().toJson(map);
				    //String content = "{\"to\":\""+number+"\",\"content\":\"手机验证码："+code+"\"}";
					Map<String, String> params = new HashMap<String, String>();
					params.put(param, content);
					try {
						String string  = HttpUtil.getInstance().doPost(url, params);
						//将电话号和验证码放入redis中
						RedisUtil.getInstance().setString(RedisKeyConstant.PHONECODE+number, 1*60*60, String.valueOf(code));
						return true;
					} catch (Exception e) {
						return false;
					}
			    }else{
			    	return false;
			    }
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	/**手机获取验证码验证
	 * @author:wuqiwei
	 * @param @param tuser
	 * @param @return
	 * @date:2015年12月7日下午3:13:00
	*/
	public Boolean codeVerification(TUser tuser) {
		String phonecode = RedisUtil.getInstance().getString(RedisKeyConstant.PHONECODE+tuser.getUsercode());
		if(tuser.getCode().equalsIgnoreCase(phonecode)){
			return true;
		}else{
			return false;
		}	
	}
	/**重置密码
	 * @author:wuqiwei
	 * @param @param tuser
	 * @param @return
	 * @date:2015年12月17日上午10:19:05
	*/
	public boolean resetPassword(TUser tuser) {
		boolean flag =true;
		TUser user = getUserDetail(tuser.getUsercode(),tuser.getUsertype());
		if(user != null){
			String newpass = EncryptUtil.encryptMd5Password2(tuser.getPassword());
			String sql = "update t_user set password=:password where usercode=:usercode and usertype=:usertype";
			tuser.setPassword(newpass);
			int i=getDao().executeSQL(sql,tuser);
			if(i == -1){
				flag=false;
				return flag;
			}
		}
		return flag;
	}
	/**获取所有管理员
	 * @author:wuqiwei
	 * @param @param tuser
	 * @param @return
	 * @date:2016年2月29日下午3:35:13
	*/
	public Map getAllAdmin(TUser tuser) {
		String sql = "SELECT * FROM t_user tu "
				+ " LEFT JOIN(SELECT tdu.departmentcode,tdu.userkey FROM t_departmentcode_user tdu) td "
				+ " ON tu.userkey = td.userkey "
				+ " LEFT JOIN(SELECT tp.departmentcode,tp.department,tp.office FROM t_department tp) tdp "
				+ " ON tdp.departmentcode = td.departmentcode ";
		if(tuser.getUsertype()!=null && tuser.getUsertype() != 10){
			sql += " where tu.usertype = :usertype";
		}
		if(tuser.getDepartmentcode() != null && tuser.getDepartmentcode().length() > 0){
			sql +=" and td.departmentcode = :departmentcode"; 
		}
		List<Object[]> list  = getDao().queryBySQL(sql,tuser);
		List<TUser> result = new ArrayList<TUser>();
		for (Object[] obj : list) {
			TUser user = new TUser();
			user.setUsercode(String.valueOf(obj[1]));
			user.setAlias(String.valueOf(obj[4]));
			user.setUsertype(Integer.parseInt(String.valueOf(obj[9]) == "null" ? "0" :String.valueOf(obj[9])));
			user.setIslock(Integer.parseInt(String.valueOf(obj[5])) == 1 ? true :false);
			user.setDepartmentcode(String.valueOf(obj[23]));
			result.add(user);
		}
		Map map = new HashMap();
		map.put("data", result);
		return map;
	}
}
